package cn.com.xiaoshoujia.wxpay.controller;

import cn.com.xiaoshoujia.activities.entity.Activity;
import cn.com.xiaoshoujia.activities.exception.ActivityException;
import cn.com.xiaoshoujia.activities.service.ActivitiesService;
import cn.com.xiaoshoujia.order.entity.Order;
import cn.com.xiaoshoujia.order.service.OrderService;
import cn.com.xiaoshoujia.user.entity.ActivityTeamHead;
import cn.com.xiaoshoujia.utils.DateUtils;
import cn.com.xiaoshoujia.utils.Result;
import cn.com.xiaoshoujia.utils.SALES;
import cn.com.xiaoshoujia.wxpay.config.WeixinPayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;


/**
 * Created by yangrui on 2017/7/19.
 */
@RestController
public class WxpayController {

    private Logger logger = LoggerFactory.getLogger(WxpayController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private ActivitiesService activitiesService;

    /**
     * @Author: yangrui
     * @Description: pid 产品唯一ID,amount 数量,money 总价,attach 附加信息
     * @Date: 下午5:56 2017/7/20
     */
    @PostMapping(value = "wxpay")
    public Object getWxPay(String orderId, String money, HttpServletRequest request, HttpServletResponse response) {
        logger.info("team wx wxpay 支付开始");
        try {
            Order order = orderService.findByOrderId(orderId);
            if (order == null) {
                return SALES.encryption(request, response, new Result("FAIL", "该订单不存在"));
            } else {
                /*订单状态*/
                Integer status = order.getStatus();
                switch (status) {
                    case -1:
                        return SALES.encryption(request, response, new Result("FAIL", "该订单已取消"));
                    case 0:
                        Long fkActivitiesId = order.getFkActivitiesId();
                        Activity activity = activitiesService.findWxStatusById(fkActivitiesId);
                        if (activity == null) {
                            return SALES.encryption(request, response, new Result("FAIL", "该拼团活动不存在"));
                        } else {
                            if (activity.getStatus().equals(0)) {
                                return SALES.encryption(request, response, new Result("FAIL", "该拼团活动已被删除"));
                            }
                            if (activity.getActivitiesStatus().equals(1)) {
                                return SALES.encryption(request, response, new Result("FAIL", "该拼团活动正在暂停中"));
                            }
                            boolean aBoolean = Long.valueOf(DateUtils.date2TimeStamp(activity.getEndTime())) < System.currentTimeMillis();
                            if (activity.getActivitiesStatus().equals(2) || aBoolean) {
                                return SALES.encryption(request, response, new Result("FAIL", "该拼团活动已过期"));
                            }
                            /*0 团, 1 单买, 此处判断团成功状态 */
                            if (order.getType().equals(0)) {
                                ActivityTeamHead activityTeamHead = activitiesService.findWxHeadById(order.getTeamId());
                                if (activityTeamHead == null) {
                                    return SALES.encryption(request, response, new Result("FAIL", "该团不存在"));
                                }
                                if (activityTeamHead.getStatus().equals(3)) {
                                    return SALES.encryption(request, response, new Result("FAIL", "该团已组团成功"));
                                }
                                if (activityTeamHead.getStatus().equals(-1)) {
                                    return SALES.encryption(request, response, new Result("FAIL", "该团已失败"));
                                }
                            }
                            if (order.getPrice() != null) {
                                BigDecimal trueMoney = order.getPrice();
                                String total_fee = String.valueOf(trueMoney);
                                String fee = "";
                                if (total_fee.endsWith("0")) {
                                    fee = total_fee.substring(0, total_fee.length() - 1);
                                }
                                logger.info("team wx wxpay 客户端价格{}", money);
                                logger.info("team wx wxpay 真实1价格,{}", total_fee);
                                logger.info("team wx wxpay 真实2价格,{}", fee);
                                logger.info("team wx wxpay 真实3价格,{}", String.valueOf(trueMoney.intValue()));
                                if (!(money.equals(total_fee) || money.equals(fee) || money.equals(String.valueOf(trueMoney.intValue())))) {
                                    return SALES.encryption(request, response, new Result("FAIL", "该产品价格有问题，请与管理员联系"));
                                }
                                total_fee = String.valueOf(trueMoney.multiply(BigDecimal.valueOf(100)).intValue());
                                String h5 = WeixinPayConfig.getH5(activity.getTitle(), total_fee, order.getSysId(), order.getOrderId(), request);
                                logger.info("team wx wxpay h5数据{}", h5);
                                return SALES.encryption(request, response, new Result("SUCCESS", h5));
                            } else {
                                return SALES.encryption(request, response, new Result("FAIL", "价格为空"));
                            }
                        }
                    case 1:
                        return SALES.encryption(request, response, new Result("FAIL", "该订单已支付"));
                    case 2:
                        return SALES.encryption(request, response, new Result("FAIL", "该订单已支付失败"));
                }
                return SALES.encryption(request, response, new Result("FAIL", ""));
            }
        } catch (ActivityException e) {
            logger.error("team wx wxpay {}", e.message);
            return SALES.encryption(request, response, new Result("FAIL", e.message));
        }
    }
}
